package com.edward.weather.strategy;

import com.edward.weather.model.WeatherData;
import com.edward.weather.vo.request.WeatherRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class WeatherApiContext {
    @Autowired
    private Map<String,WeatherApiStrategy> weatherApiStrategyMap;
    private int openWeatherMapCount = 0;
    private int gaodeCount = 0;

    private int qweatherCount = 0;

    public WeatherData fetchWeather(String city) {
        try {
            if (qweatherCount < 1000){
                WeatherApiStrategy qweatherStrategy = weatherApiStrategyMap.get("qweather");
                gaodeCount++;
                return qweatherStrategy.getWeather(city);
            }else if (openWeatherMapCount < 3000) {
//                WeatherApiStrategy openweatherMap = weatherApiStrategyMap.get("openweatherMap");
                openWeatherMapCount++;
//                return openweatherMap.getWeather(city);
                return null;
            } else if (gaodeCount < 5000) {
//                WeatherApiStrategy gaodeApiStrategy = weatherApiStrategyMap.get("gaode");
                gaodeCount++;
//                return gaodeApiStrategy.getWeather(city);
                return null;
            }else {
                throw new RuntimeException("API limit exceeded");
            }
        } catch (Exception e) {
            // Fallback to Gaode if OpenWeatherMap fails
            return null;
        }
    }

    public WeatherData dayWeather(WeatherRequestVO weatherRequestVO) {
        if (qweatherCount < 1000){
            WeatherApiStrategy qweatherStrategy = weatherApiStrategyMap.get("qweather");
            gaodeCount++;
            return qweatherStrategy.dayWeather(weatherRequestVO);
        }else if (openWeatherMapCount < 3000) {
//            WeatherApiStrategy openweatherMap = weatherApiStrategyMap.get("openweatherMap");
            openWeatherMapCount++;
//            return openweatherMap.dayWeather(weatherRequestVO);
            return null;
        } else if (gaodeCount < 5000) {
//            WeatherApiStrategy gaodeApiStrategy = weatherApiStrategyMap.get("gaode");
            gaodeCount++;
//            return gaodeApiStrategy.dayWeather(weatherRequestVO);
            return null;
        }else {
            throw new RuntimeException("API limit exceeded");
        }
    }

    public WeatherData indices(WeatherRequestVO weatherRequestVO) {
        return null;
    }
}
